package com.wowangz.cms.systemmanage.imrecord.api;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.wowangz.cms.common.utils.DataFormat;
import com.wowangz.cms.component.datagrid.pojo.DataGrid;
import com.wowangz.cms.component.datagrid.pojo.DataResult;
import com.wowangz.cms.component.datagrid.pojo.DataStyle;
import com.wowangz.cms.component.datagrid.pojo.PangingParam;
import com.wowangz.cms.component.datagrid.utils.DataTypeConstant;
import com.wowangz.cms.component.datagrid.utils.PangingTools;
import com.wowangz.cms.syscore.IssTransactionContainer;
import com.wowangz.cms.syscore.api.BaseController;
import com.wowangz.cms.syscore.api.JSONFactory;
import com.wowangz.cms.syscore.utils.ServletUtils;
import com.wowangz.cms.systemmanage.imrecord.entity.ImRecord;
import com.wowangz.cms.systemmanage.imrecord.entity.ImRecordBean;
import com.wowangz.cms.systemmanage.imrecord.service.ImRecordService;
import com.wowangz.cms.systemmanage.imrecord.service.ImUserRoleService;


@Scope("prototype")
@Controller
public class ImRecordController extends BaseController{

	private static Logger logger = LoggerFactory.getLogger(ImRecordController.class);
	
	
	
	
	@RequestMapping(value = "/systemmanage/imrecord/queryImRecordInfo.web")
	public String queryCallRecordList(HttpServletRequest request, HttpServletResponse response, Model model) {
		//获取时间段
		String startTime = DataFormat.formatDate(DataFormat.getPreQueryDatebox(new Date()), DataFormat.DT_YYYY_MM_DD);
		String endTime = DataFormat.formatDate(DataFormat.getNowDay(new Date()), DataFormat.DT_YYYY_MM_DD);
		model.addAttribute("startTime", startTime);
		model.addAttribute("endTime", endTime);
		model.addAttribute("flow_id","C9e9026473841443f888e47f82b68521d");
		return "/WEB-INF/jsp/systemmanage/exportreport/imrecordList";
	}

	/**
	 * 
	 * @Description: 获取聊天记录
	 * @return void
	 * @author Green.Long
	 * @date 2016年8月14日 下午11:28:27
	 */
	@RequestMapping(value = "/systemmanage/imrecord/queryImRecordInfoDataGrid.json")
	public void queryReportListInfoDataGrid(HttpServletRequest request, HttpServletResponse response, Model model) {

		PangingParam pangingParam = null;
		DataResult dataResult = new DataResult();
		DataGrid dataGrid = null;
		try {
			pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			HashMap<String, Object> map = (HashMap) ServletUtils.getParametersToHashMap(request);
			dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);

			map.put("startrow", 0);
			map.put("endrow", 1000);
			map.put("rows", 1000);
			map.put("sort", dataGrid.getSort());
			map.put("order", dataGrid.getOrder());

			ImRecordService imRecordService = (ImRecordService) IssTransactionContainer.getInstance(ImRecordService.class, false);
			
			String flow_id = (String)map.get("flow_id");
			
			
			
			//translatorIds.add("8b6eed66d8b043738b7e3fca813ac1c6");
			
			ImRecordBean irb = null;
			ImRecordBean header = new ImRecordBean();
			List<ImRecordBean> listimrbs = new LinkedList<ImRecordBean>();
			
			List<ImRecord> resultList = null;
			if(flow_id != null && !"".equals(flow_id)){
				 resultList = imRecordService.findImRecords(flow_id);
				//译员id列表
				ImUserRoleService imUserRoleService = (ImUserRoleService) IssTransactionContainer.getInstance(ImUserRoleService.class, false);
				List<String> translatorIds = imUserRoleService.getAllTranslator();
				
				//im聊天者是否是译员的判断
				DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				int index = 0;
				for (ImRecord imrecord : resultList) {
					
					    index++;
					    irb = new ImRecordBean();
						irb.setTime(df.format(new Date(imrecord.getTime())));
						String fromuserid = imrecord.getOwnerJid();
						String touserid = imrecord.getWithJid();
						
						fromuserid = fromuserid.substring(0,fromuserid.lastIndexOf("@"));
						touserid = touserid.substring(0,touserid.lastIndexOf("@"));
						
						if("Image".equalsIgnoreCase(imrecord.getSubject())){
							String body = "<img src='"+imrecord.getBody()+"'>";
							imrecord.setBody(body);
						}
						
						if(translatorIds.contains(fromuserid)){
							//译员
							irb.setRightmsg(irb.getTime() +"</br>"+imrecord.getBody());
							irb.setLeftmsg("");
							header.setLeftmsg("用户编号：" + touserid);
							header.setRightmsg("译员编号：" + fromuserid);
						}else{
							//用户
							irb.setRightmsg("");
							irb.setLeftmsg(irb.getTime() +"</br>"+ imrecord.getBody());
							
							header.setLeftmsg("用户编号：" + fromuserid);
							header.setRightmsg("译员编号：" + touserid);
						}
						irb.setImuserid(fromuserid);
						
					listimrbs.add(irb);
				}
				
				listimrbs.add(0, header);
			}
			
			DataStyle dataStyle = new DataStyle();
			dataStyle.setPageIndex(pangingParam.getPage());
			dataStyle.setDataCount(listimrbs.size());
			dataStyle.setDataList(listimrbs);

			dataStyle.addDepict("leftmsg", DataTypeConstant.STRING);
			dataStyle.addDepict("rightmsg", DataTypeConstant.STRING);
			dataStyle.addDepict("time", DataTypeConstant.STRING);
			dataStyle.addDepict("imuserid", DataTypeConstant.STRING);
			
			dataResult = PangingTools.buildResultPagerInfo(dataStyle);

			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, userContext));
			}
			logger.info("加载聊天记录列表数据成功");
		} catch (Exception e) {
			logger.error("加载聊天记录列表数据失败",e);
			e.printStackTrace();
		}
	}
	
    public static void main(String[] args) {
    	String fromuserid = "q8224e5e7de34e7a9753e06bd00d68ad@xmpp.xjp82.com";
    	fromuserid = fromuserid.substring(0,fromuserid.lastIndexOf("@"));
    	System.out.println(fromuserid);
	}
}
